package repository

import (
	"database/sql"
	"log"

	"todolist/internal/model"
)

type UserRepository struct {
    db *sql.DB
}

func NewUserRepository(db *sql.DB) *UserRepository {
    return &UserRepository{db: db}
}

func (r *UserRepository) Create(user *model.User) error {
    log.Printf("Creating user: %+v", user)
    
    result, err := r.db.Exec(
        "INSERT INTO users (username, password) VALUES (?, ?)",
        user.Username,
        user.Password,
    )
    if err != nil {
        log.Printf("Error creating user: %v", err)
        return err
    }

    id, err := result.LastInsertId()
    if err != nil {
        log.Printf("Error getting last insert ID: %v", err)
        return err
    }

    user.ID = int(id)
    log.Printf("User created successfully with ID: %d", id)
    return nil
}

func (r *UserRepository) FindByUsername(username string) (*model.User, error) {
    user := &model.User{}
    err := r.db.QueryRow(
        "SELECT id, username, password FROM users WHERE username = ?",
        username,
    ).Scan(&user.ID, &user.Username, &user.Password)
    if err != nil {
        return nil, err
    }
    return user, nil
} 